#!/bin/bash

set -e

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/../common.sh"

function download_codes(){
  echo "# 正在下载velvet与相关文件"
  wget -t 40 -c -P $1 https://github.com/dzerbino/velvet/archive/refs/tags/v1.2.10.tar.gz
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# velvet克隆成功\033[0m"
  else
    echo -e "\033[31m# velvet克隆失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function install_velvet(){
  tar xf $1/v1.2.10.tar.gz -C $1
  mv $1/velvet-1.2.10 $1/velvet
  cd "$1"/velvet
  sed -i -e 's/-m64//g' Makefile
  make -j $(nproc) MAXKMERLENGTH=63 CC=clang
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# velvet已经安装成功\033[0m"
  else
    echo -e "\033[31m# velvet安装失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function cp_velvet(){
  mkdir -p "$2"/velvet-v1.2.10
  cp -r "$1"/velvet/* "$2"/velvet-v1.2.10
}

function write_velvet_module() {
  cat >"$1/velvet-v1.2.10/velvet_modulefiles"<<EOF
#%Module1.0
conflict velvet
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
prepend-path PATH \$pwd
EOF
}


function main() {
  is_equal_build_install_path "$1" "$2"
  download_codes "$1"
  install_velvet "$1" "$2"
  cp_velvet "$1" "$2"
  write_velvet_module "$2"
  rm -rf "$1"/velvet
}

main "$@"
